package com.zqs.grainmall.product.exception;

import com.zqs.common.exception.BizCodeEnums;
import com.zqs.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: grain-mall
 * @description: 统一异常处理
 * @author: Mr.Zhang
 * @create: 2020-10-23 15:59
 **/

//只处理com.zqs.grainmall.product.controller里面的异常
@Slf4j
//@ControllerAdvice(basePackages = "com.zqs.grainmall.product.controller")
@RestControllerAdvice(basePackages = "com.zqs.grainmall.product.controller")
public class GrainmallExceptionControllerAdvice {

    /**
     * @ExceptionHandler 作用在方法上，代表处理什么类型的异常
     *
     * */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型:{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            //fieldError.getField(): 获取异常的字段名
            //fieldError.getDefaultMessage(): 获取到错误提示(字段上的自定义的消息提示，如果没写则默认)
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });

        return R.error(BizCodeEnums.VALID_EXCEPTION.getCode(),BizCodeEnums.VALID_EXCEPTION.getMsg()).put("data",errorMap);

    }


    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){

        log.error("错误: ",throwable);

        return R.error(BizCodeEnums.UNKNOW_EXCEPTION.getCode(),BizCodeEnums.UNKNOW_EXCEPTION.getMsg());

    }

}
